import ReactDOM from "react-dom/client";
import { configureStore } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import createSagaMiddleware from "redux-saga";
import { RouterProvider } from "react-router-dom";
import { Toast, Dialog } from "antd-mobile";
import router from "./router";
import rootReducer from "./store/root-reducers";
import rootSaga from "./store/root-sagas";
import "./assets/reset.css";
import "./assets/fonts/iconfont.css";
import sm4 from "@common/sm4";
import {
  createAction,
  subscribeScanEvent,
  unSubscribeScanEvent,
  callNativeApi
} from "@common/utils";
import { NATIVE_CLASS, SM4_KEY } from "@common/constants";
import {
  POP_PAGE_STACK,
  SET_SCAN_DATA,
} from "./store/global-state/action-types";

let backButtonPressed = false;

const handleScan = (e) => {
  window.app.store.dispatch(createAction(SET_SCAN_DATA, e.scannerdata));
};

const bindEvent = () => {
  document.addEventListener(
    "deviceready",
    function () {
      callNativeApi({
        classFullName: NATIVE_CLASS.DeviceHandler,
        action: "getAndroidId",
        params: {},
        needNonce: false,
      }).then((resp) => {
        let response = resp.data ? resp.data : resp;
        if (response.result.status !== "SUCCESS") {
          Dialog.alert({ content: response.result.errorMessage });
        } else {
          let encAndroidId = sm4.encode({
            input: response.payload.id,
            key: SM4_KEY,
          });
          window.localStorage.setItem("androidId", encAndroidId);
        }
        return;
      }).catch((err) => console.log(err));

      // 添加软键盘事件监听器
      window.addEventListener("keyboardDidShow", (e) => {
        document.getElementById("root").style.marginBottom =
          e.keyboardHeight + "px";
        document.activeElement.scrollIntoView({
          behavior: "smooth",
          block: "center",
        });
      });
      window.addEventListener("keyboardDidHide", () => {
        document.getElementById("root").style.marginBottom = 0;
      });

      // // 注册扫码事件
      const subscribe = () => subscribeScanEvent(handleScan);
      const unsubscribe = () => unSubscribeScanEvent(handleScan);
      document.addEventListener("resume", subscribe);
      document.addEventListener("pause", unsubscribe);
      subscribe();

      // 注销扫码监听
      window.plugins.OnDestroyPlugin.setEventListener(() => unsubscribe());
    },
    false
  );

  // 返回按钮双击退出
  document.addEventListener("backbutton", () => {
    let rootState = window.app.store.getState();
    let pageStack = rootState.globalState.pageStack;
    if ([0, 1].includes(pageStack.length)) {
      if (backButtonPressed) {
        navigator.app.exitApp();
      } else {
        backButtonPressed = true;
        Toast.show({ content: "再按一次退出程序", maskClickable: false });
        setTimeout(function () {
          backButtonPressed = false;
        }, 1000);
      }
    } else {
      window.app.store.dispatch(createAction(POP_PAGE_STACK));
      router.navigate(pageStack[pageStack.length - 1]);
    }
  });
};

const AppStarter = {
  setUp() {
    if ("cordova" in window) {
      bindEvent();
    }

    const sagaMiddleware = createSagaMiddleware();
    const store = configureStore({
      reducer: rootReducer,
      middleware: () => [sagaMiddleware],
    });
    sagaMiddleware.run(rootSaga);

    window.app = { store };

    ReactDOM.createRoot(document.getElementById("root")).render(
      <Provider store={store}>
        <RouterProvider router={router} />
      </Provider>
    );
  },
};

AppStarter.setUp();
